package com.bootdo.wx.api;

import cn.hutool.core.map.MapUtil;
import com.bootdo.common.utils.PageHelperUtils;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.StringUtils;
import com.bootdo.wx.dao.CmsContentDao;
import com.bootdo.wx.domain.GoodsGoodsDO;
import com.bootdo.wx.domain.GoodsProductDO;
import com.bootdo.wx.domain.MemberAddressDO;
import com.bootdo.wx.domain.MemberUserDO;
import com.bootdo.wx.service.*;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by HP on 2019/5/29.
 */
@Controller
@RequestMapping("/api/memberCart")
public class ApiMemberCartController {

    @Autowired
    private MemberCartService memberCartService;
    @Autowired
    private MemberUserService memberUserService;
    @Autowired
    private GoodsProductService goodsProductService;
    @Autowired
    private GoodsGoodsService goodsGoodsService;
    @Autowired
    private CmsContentDao cmsContentDao;
    @Autowired
    private OrderOrderService orderOrderService;
    @Autowired
    private MemberAddressService memberAddressService;

    /**
     * 购物车添加
     * @param map
     * @return
     */
    @RequestMapping("/addCart")
    @ResponseBody
    public R addCart(@RequestBody Map<String, Object> map){
        try {
            if (!map.containsKey("userId") || StringUtils.isBlank(map.get("userId").toString())
                    || !map.containsKey("goodsId") || StringUtils.isBlank(map.get("goodsId").toString())
                    || !map.containsKey("productId") || StringUtils.isBlank(map.get("productId").toString())
                    || !map.containsKey("addressId") || StringUtils.isBlank(map.get("addressId").toString())
                    || !map.containsKey("num") || StringUtils.isBlank(map.get("num").toString())
                    ){
                return R.error("购物车添加参数错误");
            }
            Map<String,Object> params = new HashMap<String,Object>();
            params.put("userId",map.get("userId"));
            params.put("xId",map.get("goodsId"));
            params.put("productId",map.get("productId"));
            params.put("num",map.get("num"));
            params.put("type",0);
            R r = goodsGoodsService.isCanBye(params);
            if (Integer.valueOf(r.get("code").toString()) != 0) {
                return r;
            }
            return memberCartService.add(map);
        } catch (Exception e) {
            e.printStackTrace();
            return R.error("添加购物车失败");
        }
    }

    /**
     * 购物车查询
     * @param map
     * @return
     */
    @RequestMapping("/getList")
    @ResponseBody
    public R getList(@RequestBody Map<String, Object> map){
        try {
            if (!map.containsKey("userId") || StringUtils.isBlank(map.get("userId").toString())){
                return R.error("购物车参数错误");
            }
            String userId = map.get("userId").toString();
            MemberUserDO userDO = memberUserService.get(userId);
            if (userDO==null){
                return R.error("登录信息异常");
            }
            //查询所有地址
            List<Map<String, Object>> list = memberCartService.getCartListBuyUser(map);
            return R.ok().put("data", list);
        } catch (Exception e) {
            return R.error("购物车查询失败");
        }
    }

    /**
     * 购物车删除
     * @param map
     * @return
     */
    @RequestMapping("/cartRemove")
    @ResponseBody
    public R cartRemove(@RequestBody Map<String, Object> map){
        try {
            if (!map.containsKey("cartList") || StringUtils.isBlank(map.get("cartList").toString())
                    ||!map.containsKey("userId") || StringUtils.isBlank(map.get("userId").toString())
                    ){
                return R.error("参数错误");
            }
            List<String> cartList = (List<String>)(map.get("cartList")); //商品集合
            map.put("ids", cartList);
            memberCartService.removeByUserIdAndCardId(map);
            return R.ok("删除成功");
        } catch (Exception e) {
            return R.error("购物车删除失败");
        }
    }

    /**
     * 购物车修改
     * @param map
     * @return
     */
    @RequestMapping("/editCart")
    @ResponseBody
    public R addAndSub(@RequestBody Map<String, Object> map){
        try {
            if (!map.containsKey("cartId") || StringUtils.isBlank(map.get("cartId").toString())
                    || !map.containsKey("num") || StringUtils.isBlank(map.get("num").toString())
                    || !map.containsKey("userId") || StringUtils.isBlank(map.get("userId").toString())
                    ){
                return R.error("参数错误");
            }
            return memberCartService.editCart(map);
        } catch (Exception e) {
            return R.error("购物车修改失败");
        }
    }

    /**
     * 购物车 确认订单
     * @param map
     * @return
     */
    @RequestMapping("/enter")
    @ResponseBody
    public R enter(@RequestBody Map<String, Object> map){
        try {
             if (!map.containsKey("cartList") || StringUtils.isBlank(map.get("cartList").toString())
                    || !map.containsKey("userId") || StringUtils.isBlank(map.get("userId").toString())){
                return R.error("参数错误");
            }
            String userId = map.get("userId").toString();
            MemberUserDO userDO = memberUserService.get(userId);
            int level = 0;
            if (userDO != null) {
                map.put("level", userDO.getLevel());
                level = userDO.getLevel();
            } else {
                map.put("level", 0);
                level = 0;
            }
            BigDecimal allPostFee = new BigDecimal(0);
            int allNum = 0;
            BigDecimal allPrice = new BigDecimal(0);
            List<Map<String,Object>> list = new ArrayList<>();
            PageHelperUtils.page(map);
            list = memberCartService.getCartListBuyIds(map);
            //判断购买量
            for (Map<String,Object> cartMap : list) {
                String productId = cartMap.get("product_id").toString();
                String goodsId = cartMap.get("goods_id").toString();
                GoodsProductDO productDO = goodsProductService.get(productId);
                GoodsGoodsDO goodsDO = goodsGoodsService.get(goodsId);
                String goodsName = goodsDO.getName();
                //int isvip = goodsDO.getIsvip();  //是否参与会员活动 0：不参与，1：参与
                int num = Integer.valueOf(cartMap.get("num").toString()); //购买量
                allNum = allNum+num;
                BigDecimal minePrice = new BigDecimal(0);

                    switch (level) {
                        case 1 :
                            minePrice = productDO.getPriceC();
                            break;
                        case 2 :
                            minePrice = productDO.getPriceZ();
                            break;
                        case 3 :
                            minePrice = productDO.getPriceG();
                            break;
                        default:
                            minePrice = productDO.getPrice();
                    }

                cartMap.put("minePrice",minePrice);
                allPrice = allPrice.add(minePrice.multiply(new BigDecimal(num)));
                int min = productDO.getBuyMin();
                int max = productDO.getBuyMax();
                if (num < min) {
                    return R.error(goodsName+" 最小购买量为"+min);
                } else if (num > max) {
                    return R.error(goodsName+" 最大购买量为"+max);
                }
                //计算运费
                Map<String,Object> postMap = new HashMap<>();
                postMap.put("addressId", MapUtil.getStr(cartMap,"addressId"));
                postMap.put("total", num);
                BigDecimal postFees = orderOrderService.getPostFees(postMap, goodsId, productId, 1);
                cartMap.put("postFee",postFees);
                allPostFee=allPostFee.add(postFees);
                cartMap.put("xjPrice",minePrice.multiply(new BigDecimal(num)).add(postFees)); //小计金额
                allPrice= allPrice.add(postFees).add(productDO.getRebateOne());
                //地址
                MemberAddressDO memberAddressDO = memberAddressService.get(cartMap.get("addressId").toString());
                cartMap.put("fullName",memberAddressDO.getFullName());
                cartMap.put("fullPhone",memberAddressDO.getPhone());
                cartMap.put("address",memberAddressDO.getProvince()+" "+memberAddressDO.getCity()+" "+memberAddressDO.getCounty()+" "+memberAddressDO.getAddress() );

            }
            PageInfo<Map<String,Object>> pageInfo = new PageInfo<>(list);
            return R.ok().put("data", pageInfo).put("allPostFee",allPostFee).put("allNum",allNum).put("allPrice",allPrice);
        } catch (Exception e) {
            return R.error("购物车确认失败");
        }
    }


}
